package insert;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import ressource.CadreVendeur;

/**
 * Servlet implementation class AjoutAvatar
 */
public class AjoutAvatar extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AjoutAvatar() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setAttribute("phrase", "Plus assez beau ?");
		getAvatar(request, response);
		
		RequestDispatcher dis=request.getRequestDispatcher("updateavatar.jsp");
		dis.forward(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		RequestDispatcher dis;
		Connection con = null;
		
		Integer membre = (Integer)session.getAttribute("user_id");
		if(membre == null){
			dis=request.getRequestDispatcher("updateavatar.jsp");
			dis.forward(request, response);
			return;
		}
		
		//Commençons par gérer l'upload
		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		String fileName = null;
		Context namingContext;
		try {
			List items = upload.parseRequest(request);
			Iterator iterator = items.iterator();
			FileItem item = (FileItem) iterator.next();
			if (! item.isFormField()) {
				FileItem photo = item;
			    	
			   	//Et maintenant l'upload à proprement parler :
			   	 fileName = photo.getName();
			   	 if(! fileName.isEmpty()) {
	                 String root = getServletContext().getRealPath("/");
	                 File path = new File(root + "/images/avatars");
	                 if (!path.exists()) {
	                     boolean status = path.mkdirs();
	                 }
	
	                 File uploadedFile = new File(path + "/" + fileName);
	                 try {
	                	 photo.write(uploadedFile);
	                 } catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
	                 }
	                 
	                try {
	         			namingContext = new InitialContext();
	         			DataSource dataSource = (DataSource)namingContext.lookup("java:comp/env/jdbc/MiniIBay");
	         			con = dataSource.getConnection();
	         		
	         			 //Et on enregistre ce nouvel avatar dans la bdd :
		                 PreparedStatement update = con.prepareStatement("UPDATE membre SET avatar = ? WHERE id_membre = ?");
		                 update.setString(1, fileName);
		                 update.setInt(2, membre);
		                 update.executeUpdate();
		                 request.setAttribute("phrase", "Ah oui, c'est mieux maintenant !");
	                 } catch (NamingException e) {
	         			// TODO Auto-generated catch block
	         			e.printStackTrace();
	         		} catch (SQLException e) {
	         			// TODO Auto-generated catch block
	         			e.printStackTrace();
	         		}finally{
	         			if(con != null){
	         				try {
	         					con.close();
	         				} catch (SQLException e) {
	         					// TODO Auto-generated catch block
	         					e.printStackTrace();
	         				}
	         			}
	         		}
				}
			} else {
				List<String> erreur = new LinkedList<String>();
				erreur.add("Pour changer votre photo, choisissez une photo.");
				request.setAttribute("erreur", erreur);
				getAvatar(request, response);
				dis=request.getRequestDispatcher("ajoutavatar.jsp");
				dis.forward(request,response);
			}
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		getAvatar(request, response);
		dis=request.getRequestDispatcher("updateavatar.jsp");
		dis.forward(request,response);
	}
	
	public void getAvatar (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		RequestDispatcher dis;
		Connection con = null;
		Context namingContext;
		
		Integer membre = (Integer)session.getAttribute("user_id");
		if(membre == null){
			dis=request.getRequestDispatcher("updateavatar.jsp");
			dis.forward(request, response);
			return;
		}
		
		try {
 			namingContext = new InitialContext();
 			DataSource dataSource = (DataSource)namingContext.lookup("java:comp/env/jdbc/MiniIBay");
 			con = dataSource.getConnection();
 		
 			 //Et on enregistre ce nouvel avatar dans la bdd :
             PreparedStatement select = con.prepareStatement("SELECT avatar FROM membre WHERE id_membre = ?");
             select.setInt(1, membre);
             ResultSet rs = select.executeQuery();
             CadreVendeur v = new CadreVendeur();
             if(rs.next()) {
            	 v.setAvatar(rs.getString("avatar"));
             } else {
            	 v.setAvatar(null);
             }
             request.setAttribute("vendeur", v);
             
        } catch (NamingException e) {
 			// TODO Auto-generated catch block
 			e.printStackTrace();
 		} catch (SQLException e) {
 			// TODO Auto-generated catch block
 			e.printStackTrace();
 		}finally{
 			if(con != null){
 				try {
 					con.close();
 				} catch (SQLException e) {
 					// TODO Auto-generated catch block
 					e.printStackTrace();
 				}
 			}
 		}
	}

}
